package org.dao.imp;

import java.util.List;

import org.dao.UserDao;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.pojo.User;
import org.util.HibernateSessionFactory;

/**
 * 
 * @author hasee
 * 添加session 和 transaction 对象属性，并在构造函数中实例化
 */
public class UserDaoImp implements UserDao {
	
	private Session session;
	private Transaction ts;
	
	
	public UserDaoImp() {
		super();
		session = HibernateSessionFactory.getSession();
		Transaction ts = session.beginTransaction();
	}

	@Override
	public boolean addUser(User newUser) {
		session.save(newUser);
		ts.commit();
		return false;
	}

	@Override
	public List<User> findAllUser() {
		Query query = session.createQuery("from User");
		List<User> list = query.list();
		return list;
	}

	@Override
	public User findUser(int id) {
		Query query = session.createQuery("from User where id=?");
		query.setParameter(1, id);
		List<User> list = query.list();
		User user = list.get(0);
		return user;
	}

	@Override
	public boolean updateUser(User existUser) {
		session.saveOrUpdate(existUser);
		ts.commit();
		return true;
	}

	@Override
	public boolean deleteUser(User delUser) {
		session.delete(delUser);
		
		return true;
	}

}
